package com.example.cobodynamicproxydemo.service;

import com.example.cobodynamicproxydemo.interceptors.UserApiInterceptor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

@Slf4j
public class UserApiExecution {

    private final UserApiDemoClient userApiDemoClient;

    private final Iterator<UserApiInterceptor> interceptors;

    /**
     * 构建执行实例
     *
     * @param userApiDemoClient 执行对象
     * @param interceptors      拦截器执行链
     */
    public UserApiExecution(UserApiDemoClient userApiDemoClient, List<UserApiInterceptor> interceptors) {
        this.userApiDemoClient = userApiDemoClient;
        this.interceptors = interceptors.iterator();
    }

    @SneakyThrows
    public Object execute(Method method, Object[] args) {
        if (interceptors.hasNext()) {
            //  获取下个拦截器
            UserApiInterceptor next = interceptors.next();
            return next.interceptor(method, args, this);
        }
        log.info("[execution]执行原始方法: {}", args);
        return method.invoke(userApiDemoClient, args);
    }


}
